<?php
namespace app\admin\model;

use think\facade\Db;
use think\Model;
use think\facade\Request;
use think\model\concern\SoftDelete;

class Users extends Model
{
    use SoftDelete;
    protected $pk = 'id';
    protected $deleteTime = 'delete_time';
    public static function getUserList($where,$param,$data)
    {
        $list = Users::alias('u')
            ->field('u.*')
            ->field('ag.title')
            ->where($where,$param,$data)
            ->join('ecm_auth_group ag','ag.id=u.author')
            ->paginate([
                'list_rows'=>5,
            ]);
        return $list;
    }
    //单个软删除
    public static function usersDel($get)
    {
        $res = Users::destroy($get['id']);
        return $res;
    }
    //多个软删除
    public static function usersDels($get)
    {
        $id = explode(',',$get['id']);
        $res = Users::destroy($id);
        return $res;
    }
    //添加
    public static function addUsersAttr($add)
    {
        //添加
        try{
            $res = Users::strict(true)->save($add);
        }catch (\Exception $e){
            $res = false;
            echo $e->getMessage();
        }
        return $res;
    }
    //登录
    public static function loginList($where)
    {
        $list = Users::where($where)->find();
        return $list;
    }
    public static function loginEdit($where)
    {
        try{
            $res = Users::update($where);
        }catch (\Exception $e){
            $res = false;
        }
        return $res;
    }
    //修改用户列表
    public static function editUserInfo($get,$edit)
    {
        // 启动事务
        Db::startTrans();
        if (Request::post()) {
            try {
                $res = Users::update($edit);
                $data = [
                    'uid' =>$edit['id'],
                    'group_id' =>$edit['author']
                ];
                AuthGroupAccess::update($data);
                $msg = '成功';
                // 提交事务
                Db::commit();
            } catch (\Exception $e) {
                $res = false;
                $msg = $e->getMessage();
                // 回滚事务
                Db::rollback();
            }
            return [$res,$msg];
        }
        $list = Users::field(true)
            ->where('id','=',$get['id'])
            ->find()->toArray();
        return $list;
    }
    public static function addUserInfo($add)
    {
        // 启动事务
        Db::startTrans();
        try{
            $res = Users::insertGetId($add);
            $data = [
                'uid'   =>$res,
                'group_id'=>$add['author'],
            ];
            AuthGroupAccess::insert($data);
            $msg = '成功';
            // 提交事务
            Db::commit();
        }catch (\Exception $e){
            $res = false;
            $msg = $e->getMessage();
            // 回滚事务
            Db::rollback();
        }
        return [$res,$msg];
    }


}